package com.jt.interceptor;

import com.jt.pojo.User;
import com.jt.thread.UserThreadLocal;
import com.jt.util.CookieUtil;
import com.jt.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 业务说明:
     *  如果用户已经登录则程序放行,否则拦截
     * 判断依据:1.是否有cookie  2.redis中是否有记录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.动态获取京淘ticket
        String ticket = CookieUtil.getValue("JT_TICKET",request);
        if(!StringUtils.isEmpty(ticket)){
            //2.检验redis中是否有数据
            System.out.println(ticket);
            System.out.println(jedisCluster.get(ticket));
            if(jedisCluster.exists(ticket)){
                //4.动态获取用户信息,将用户信息交给redis对象传递给下一级
                String Json = jedisCluster.get(ticket);
                User user = ObjectMapperUtil.toObject(Json, User.class);
                //request.setAttribute("JT_USER",user);
                //当前对象会携带当前用户信息

                //利用thread方式传参
                UserThreadLocal.set(user);
                return true;
            }
            //3.将无效cookie删除
            CookieUtil.deleteCookie("JT_TICKET","/","jt.com",response);
        }
        response.sendRedirect("/user/login.html");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        /**
         * 利用拦截器方法清空数据
         */
        //1.删除request对象中的数据
        request.removeAttribute("JT_USER");
        //2.删除Thread中的数据
        UserThreadLocal.remove();
    }
}
